<?php
class weixin extends base{

	public function init(){ // 公用
		parent::init(); // 这是必须的

		$this->tit = "微信";
		$this->current = 'my';

		$this->sys_userObj = D('sys_user');

        $this->companyObj = D('company');
		$this->diaochaObj = D('company_diaocha');
		$this->diaocha_logObj = D('company_diaocha_log');
		$this->bingchuangObj = D('company_bingchuang');
		$this->zoneObj = D('company_zone');

        $this->userObj = D('company_user');


        require(APP_DIR.'/protected/include/lib/Wechat/Wechat.class.php');
        require(APP_DIR.'/protected/include/lib/Wechat/WechatAuth.class.php');

        $this->_token     = 'khePcWQZudbbvnKBoJbZfWrHjne1';
		$this->_weixin = new Wechat($this->_token);

        // $this->_WechatAuth = new WechatAuth($this->appid,$this->appsecret);
        // $this->accessToken = $this->_WechatAuth->getAccessToken();

        // dump($this->accessToken);exit;
	}






    public function index(){
		$data = $this->_weixin->request();
		if($data && is_array($data)){
			// 事件请求路由
			switch ($data['MsgType']) {
				case 'event':
					$this->doEvent($data);
					break;
				case 'location':
					$this->doLocation($data);
					break;
				// case 'image':
				// 	$this->doImage($data);
				// 	break;
				// case 'voice':
				// 	$this->doVoice($data);
				// 	break;
				// case 'video':
				// 	$this->doVideo($data);
				// 	break;
				// case 'link':
				// 	$this->doLink($data);
				// 	break;
				// default:
				// 	$this->doKeyword($data);
				// 	break;
			}
		}

	}

	// 发送位置信息自动回复
    private function doLocation($data) {
        //       $lat = $data['Location_X'];
        //       $lng = $data['Location_Y'];

		// if(empty($this->_detail)){
		// 	$list = D('Object')->where(array('closed' => 0,'photo'=>array('NEQ','')))->order(" (ABS(lng - '{$lng}') +  ABS(lat - '" . $lat . "') )  asc ")->limit(0, 10)->select();
		// 	if (!empty($list)) {
		// 		$content = array();
		// 		foreach ($list as $item) {
		// 			$content[] = array(
		// 				$item['title'],
		// 				$item['address'],
		// 				__HOST__.'/wap/smart/detail/id/' . $item['id'] . '.html',
		// 				__HOST__.'/upload/'.$item['photo'],
		// 			);
		// 		}
		// 		$this->_weixin->response($content, 'news');
		// 	} else {
		// 		$this->_weixin->response('很抱歉没有合适的商家推荐给您', 'text');
		// 	}
		// }else{
		// 	$distance = getDistanceCN($this->_detail['lat'],$this->_detail['lng'],$lat,$lng);
		// 	$url = 'http://restapi.amap.com/v3/distance?key='.$this->_CONFIG['site']['apikey'].'&origins='.$this->_detail['lng'].','.$this->_detail['lat'].'&destination='.$lng.','.$lat;
		// 	$this->curl = new \Think\Curl();
		// 	$str = $this->curl->get($url);
		// 	$arr = json_decode($str,true);
		// 	$drive_distance = $arr['results'][0]['distance'] / 1000;
		// 	$drive_time = $arr['results'][0]['duration'] / 60;
		// 	$weixin_msg = unserialize($this->_detail['weixin_msg']);
		// 	$text = "/::)亲离我们\n直线距离: " .$distance ."\n驾驶距离: " .$drive_distance ."公里\n驾驶时间: ".$drive_time."分钟\n<a href='".__HOST__."/wap/weixin/nav/nav/".$this->_detail['lng'].",".$this->_detail['lat']."/addr/".$this->_detail['title'].".html'>点击查看导航</a>";
		// 	$this->_weixin->response($text,'text');
		// }

    }


	// 微信事件处理
    private function doEvent($data) {
		$event = $data['Event'];
        dump_log1($data);
		switch ($event) {
			case 'subscribe':
				$this->eventSubscribe($data);
				break;
			case 'unsubscribe':
				$this->eventUnsubscribe($data);
				break;
			case 'SCAN':
				$this->eventScan($data);
				break;
			case 'LOCATION':
				$this->eventLocation($data);
				break;
			// case 'CLICK':
			// 	$this->eventClick($data);
			// 	break;
			// case 'VIEW':
			// 	$this->eventView($data);
			// 	break;
			// default:
			// 	$this->eventDefault($data);
			// 	break;
		}
	}

	//关注公众号事件
    private function eventSubscribe($data) {
		$EventKey = $data['EventKey'];
        // dump_log0($EventKey);
		//屏蔽出现的字符串
		// if(strpos($EventKey ,"last_trade_no") != -1) {
		// 	$EventKey = NULL;
		// }

        $qrscene = explode('_',$EventKey);
        $type = $qrscene[1];
        $bc_id = $qrscene[2];
        dump_log0($qrscene);
        if($type == 'bc'){
            if($bc_id){


                //记录微信用户的OPENID
                $this->createuserinfo($data['FromUserName'],$bc_id);

                $bingchuang = $this->bingchuangObj->findById($bc_id);
                if($bingchuang){
                    $zone = $this->zoneObj->findById($bingchuang['zone_id']);
                    $company = $this->companyObj->findById($bingchuang['company_id']);


                    // 创建标签
                    $tag_id = $this->create_tag($this->accessToken,$zone['name']);
                    // dump_log1($tag_id);
                    if($tag_id){
                        $res = $this->set_user_tag($this->accessToken,$data['FromUserName'],$tag_id);
                        // dump_log1($res);
                    }
                    if($zone['tag']){
                        $tag_id = $this->create_tag($this->accessToken,$zone['tag']);
                        if($tag_id){
                            $res = $this->set_user_tag($this->accessToken,$data['FromUserName'],$tag_id);
                            // dump_log1($res);
                        }
                    }

                    $content[] = array(
                        "感谢关注智慧云医护",
                        "{$zone['name']}{$bingchuang['name']}您好，诚邀您参与{$company['name']}满意度调查",
                        "https://t.20m.cn/diaocha/add?bc_id={$bc_id}'"
                        // __HOST__.'/upload/'.$this->config['weixin']['photo'],
                    );
                    //发送信息给用户
                    $this->_weixin->response($content, 'news');
                }

            }
        }

		// //普通扫描二维码关注
		// if(empty($EventKey)){

		// 	$content[] = array(
		// 		"感谢关注智慧云医护",
		// 		"#"
		// 		// __HOST__.'/upload/'.$this->config['weixin']['photo'],
		// 	);
		// 	//发送信息给用户
		// 	$this->_weixin->response($content, 'news');
		// }
	}

	//取消关注公众号事件
    private function eventUnsubscribe($data) {
		$EventKey = $data['EventKey'];
		//屏蔽出现的字符串
		if(strpos($EventKey ,"last_trade_no") != -1) {
			$EventKey = NULL;
		}

		//记录微信用户的OPENID
		$sys_user = $this->sys_userObj->find(array('open_id' => $data['FromUserName'], ));
		if($sys_user){
			$arrBase = array(
				'subscribe'=>0,
				'up_time'=>date('Y-m-d H:i:s'),
				'status'=>1,
			);
			$this->sys_userObj->edit($sys_user['id'],$arrBase);
		}

		//普通扫描二维码关注
		if(empty($EventKey)){
			// $content[] = array(
			// 	$this->config['site']['site_name'],
			// 	$this->config['site']['description'],
			// 	$this->config['site']['linkurl'],
			// 	__HOST__.'/upload/'.$this->config['weixin']['photo'],
			// );
			// //发送信息给用户
			// $this->_weixin->response($content, 'news');
		}
	}

    //关注公众号事件
    private function eventScan($data) {
		$EventKey = $data['EventKey'];
        // dump_log0($EventKey);
		//屏蔽出现的字符串
		// if(strpos($EventKey ,"last_trade_no") != -1) {
		// 	$EventKey = NULL;
		// }

        $qrscene = explode('_',$EventKey);
        $type = $qrscene[0];
        $bc_id = $qrscene[1];
        dump_log0($qrscene);
        if($type == 'bc'){
            if($bc_id){

                //记录微信用户的OPENID
                $this->createuserinfo($data['FromUserName'],$bc_id);




                $bingchuang = $this->bingchuangObj->findById($bc_id);
                if($bingchuang){
                    $zone = $this->zoneObj->findById($bingchuang['zone_id']);
                    $company = $this->companyObj->findById($bingchuang['company_id']);

                    // 创建标签
                    $tag_id = $this->create_tag($this->accessToken,$zone['name']);
                    // dump_log1($tag_id);
                    if($tag_id){
                        $res = $this->set_user_tag($this->accessToken,$data['FromUserName'],$tag_id);
                        // dump_log1($res);
                    }
                    if($zone['tag']){
                        $tag_id = $this->create_tag($this->accessToken,$zone['tag']);
                        if($tag_id){
                            $res = $this->set_user_tag($this->accessToken,$data['FromUserName'],$tag_id);
                            // dump_log1($res);
                        }
                    }

                    $content[] = array(
                        "感谢关注智慧云医护",
                        "{$zone['name']}{$bingchuang['name']}您好，诚邀您参与{$company['name']}满意度调查",
                        "https://t.20m.cn/diaocha/add?bc_id={$bc_id}'"
                        // __HOST__.'/upload/'.$this->config['weixin']['photo'],
                    );
                    //发送信息给用户
                    $this->_weixin->response($content, 'news');
                }

            }
        }

	}

	//上报位置事件
    private function eventLocation($data) {
		$lat = $data['Latitude'];
		$lng = $data['Longitude'];
		$conn = D('Connect')->getConnectByOpenid('weixin', $data['FromUserName']);
		if(!empty($conn)){
			$uid = (int) $conn['uid'];
			if($uid != 0){
				D('Users')->save(array('lat' => $lat,'lng' => $lng,'uid' => $conn['uid']));
			}else{
				$array = array();
				$array['connect_id'] = $conn['connect_id'];
				$array['lat'] = $data['Latitude'];
				$array['lng'] = $data['Longitude'];
				D('Connect')->save($array);
			}
		}else{
			$array = array();
			$array['type'] = 'weixin';
			$array['open_id'] = $data['FromUserName'];
			$array['lat'] = $data['Latitude'];
			$array['lng'] = $data['Longitude'];
			D('Connect')->add($array);
		}
	}









	public function menu()
    {
        $menuData = ' {
            "button":[
            {
                "type":"view",
                "name":"健康知识",
                "url":"http://jkjy.czmc.cn/list.html?cid=130&r=0"
            },
            {
                "name":"个人中心",
                "sub_button":[
                {
                    "type":"view",
                    "name":"我的调查",
                    "url":"http://t.20m.cn/my/index"
                },
                {
                    "type":"view",
                    "name":"调查管理",
                    "url":"http://t.20m.cn/index_admin/my/index"
                }]
            }]
        }';

        $res = $this->create_menu($menuData);
        if($res){
            echo '菜单成功';
        }else{
            echo '失败';
        }

    }


    public function create_menu($menuData){


        // $menu = array();
        // $menu[] = new \lib\MenuButton('问卷调查','click','click1');
        // $menu[] = new \lib\MenuButton('健康知识','view',null,'http://jkjy.czmc.cn/list.html?cid=130&r=0');
        // $menu[] = new \lib\MenuButton('个人中心',null,null,null,array(
        //     new \lib\MenuButton('我的调查','view',null,'http://t.20m.cn/my/index'),
        //     new \lib\MenuButton('调查管理','view',null,'http://t.20m.cn/index_admin/my/index'),
        //     // new \lib\MenuButton('二级菜单1','scancode_push','scancode_push1'),
        //     // new \lib\MenuButton('二级菜单2','scancode_waitmsg','scancode_waitmsg1'),
        //     // new \lib\MenuButton('二级菜单3','pic_sysphoto','pic_sysphoto1'),
        //     // new \lib\MenuButton('二级菜单4','pic_photo_or_album','pic_photo_or_album1')
        // ));
        // $data = array();
        // $data['button'] = array();
        // foreach($menu as $button){
        //     array_push($data['button'],$button->toArray());
        // }
        $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$this->accessToken;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $menuData);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($ch);
        curl_close($ch);

        $result = json_decode($data, true);
        // dump($result);
        if(isset($result['errcode']) && $result['errcode'] == 0){
            return true;
        }else{
            return false;
        }
    }



	//用户关注后获取用户信息
    public function createuserinfo($openid,$bc_id)
    {

        if($bc_id){
            $bingchuang = $this->bingchuangObj->findById($bc_id);
            $zone = $this->zoneObj->findById($bingchuang['zone_id']);
            $company = $this->companyObj->findById($bingchuang['company_id']);
        }
        //记录微信用户的OPENID
		$sys_user = $this->sys_userObj->find(array('open_id' => $openid, ));
		if($sys_user){
            $arrBase = array(
                // 'open_id'=>$openid,
                'add_time'   => date("Y-m-d H:i:s"),
                'status' => 1,
                'subscribe'=>1,
            );

            $this->sys_userObj->edit($sys_user['id'],$arrBase);
			// $user_id = $this->userObj->create($arrBase);
            $wxuser_id = $sys_user['id'];
		}else{
			$arrBase = array(
				'up_time'=>date('Y-m-d H:i:s'),
				'status'=>1,
				'subscribe'=>1,
			);
			$wxuser_id = $this->sys_userObj->add($arrBase);
		}
        // 加入公司用户表
        if($wxuser_id){
            $cond = "status=1 and wxuser_id='{$wxuser_id}' and company_id='{$company['id']}'";

            $user = $this->userObj->find(array($cond));
            if($user){
                $arrBase = array(
                    // 'nickname'   => $openid,
                    // 'avatarUrl'   => $info['headimgurl'],
                    'up_time'   => date("Y-m-d H:i:s"),
                    'status' => 1,
                );
                $this->userObj->edit($user['id'],$arrBase);
                $user_id = $user['id'];
            }else{
                $arrBase = array(
                    'company_id' => $company['id'],
                    'nickname'   => $openid,
                    // 'avatarUrl'   => $info['headimgurl'],
                    // 'sex'   => $info['sex'],
                    'wxuser_id'=> $wxuser_id,
                    'add_time'   => date("Y-m-d H:i:s"),
                    'status' => 1,
                );
                $user_id = $this->userObj->add($arrBase);
            }
            // $_SESSION["user"]['id'] = $user_id;
        }

        return true;
    }

    // 创建标签
    public function create_tag($access_token,$tag_name){

        $url = "https://api.weixin.qq.com/cgi-bin/tags/get?access_token={$access_token}";

        $response = file_get_contents($url);
        $result = json_decode($response, true);
        $tag_list = $result['tags'];
        // dump_log1($result);
        if($tag_list){
            foreach($tag_list as $val){
                if($tag_name == $val['name']){
                    return $val['id'];
                }
            }
        }


        // $tag_name = '标签名称';
        $url = "https://api.weixin.qq.com/cgi-bin/tags/create?access_token={$access_token}";
        $data = [
            'tag' => [
                'name' => $tag_name
            ]
        ];

        $options = [
            'http' => [
                'method' => 'POST',
                'header' => 'Content-type:application/json',
                'content' => json_encode($data,JSON_UNESCAPED_UNICODE)
            ]
        ];
        $context = stream_context_create($options);
        $response = file_get_contents($url, false, $context);

        $result = json_decode($response, true);
        $tag_id = $result['tag']['id'];
        return $tag_id;
    }


    public function set_user_tag($access_token,$openid,$tagid){
        // $openid = '用户openid';
        // $tagid = '标签id';

        $url = "https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token={$access_token}";
        $data = [
            'openid_list' => [$openid],
            'tagid' => $tagid
        ];

        $options = [
            'http' => [
                'method' => 'POST',
                'header' => 'Content-type:application/json',
                'content' => json_encode($data)
            ]
        ];
        $context = stream_context_create($options);
        $response = file_get_contents($url, false, $context);

        $result = json_decode($response, true);

        return $result;
    }


	//获取用户关注事件
    public function urlRedirect(){//公众号配置路径必须是这里，接收关注后微信传过来的参数
        if(!isset($_GET['echostr'])){
            $this->responseMsg();
        }else{
            // $this->valid();

            $nonce     = $_GET['nonce'];
            $token     = 'khePcWQZudbbvnKBoJbZfWrHjne1';
            $timestamp = $_GET['timestamp'];
            $echostr   = $_GET['echostr'];
            $signature = $_GET['signature'];
            //形成数组，然后按字典序排序
            $array = array();
            $array = array($nonce, $timestamp, $token);
            sort($array);
            //拼接成字符串,sha1加密 ，然后与signature进行校验
            $str = sha1( implode( $array ) );
            if( $str  == $signature ){
                //第一次接入weixin api接口的时候
                echo $echostr;
                exit;
            }
        }

    }


    public function responseMsg()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);
            switch($RX_TYPE){
                case "text":
                    $resultStr = $this->handleText($postObj);
                    break;
                case "event":
                    $resultStr = $this->handleEvent($postObj);
                    break;
                default:
                    $resultStr = "Unknow msg type: ".$RX_TYPE;
                    break;
            }
            echo $resultStr;
        }else {
            echo "";
            exit;
        }
    }

    public function handleText($postObj)
    {
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $keyword = trim($postObj->Content);
        $time = time();
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[%s]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>0</FuncFlag>
                    </xml>";
        if(!empty( $keyword ))
        {
            $msgType = "text";
            $contentStr = "欢迎您关注好运平台！";
            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
            echo $resultStr;
        }else{
            echo "请输入...";
        }
    }

    public function handleEvent($object)
    {
        $contentStr = "";
        switch ($object->Event)
        {
			case 'subscribe':    // 关注事件[扫描带参数二维码事件 用户未关注时事件推送]

                // $contentStr = "感谢您关注【********】"."\n".$object->ToUserName."\n".$object->FromUserName."\n".$object->FromUserName."\n".$object->MsgType."\n".$object->Event."\n".$object->EventKey."\n".$object->Ticket;
                // $openid = (string)$object->FromUserName; //数据类型转换为字符串,mmp这个问题找了好久
                $refer_id = explode('_',$object->EventKey); //$object->EventKey返回的是qrsence_123这种类型
                // $this->createuserinfo($openid,$refer_id[1]);//获取用户信息

				$contentStr = "感谢您关注【*******】{$refer_id[1]}";
				break;
			case 'unsubscribe':  // 取消关注
                $contentStr = "取消关注";
				break;
			case 'SCAN':        // 扫描带参数二维码事件 用户已关注时的事件推送
				$contentStr = "您已关注过，谢谢！";
				break;
			case 'LOCATION':    // 上报地理位置事件
                $contentStr = "上报地理位置事件";
				break;
			case 'CLICK':       // 自定义菜单事件 主菜单
                $contentStr = "CLICK";
				break;
        }
        $resultStr = $this->responseText($object, $contentStr);
        return $resultStr;
    }

    public function responseText($object, $content, $flag=0)
    {
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>%d</FuncFlag>
                    </xml>";
        $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag);
        return $resultStr;
    }


	/**
     * 发送post请求
     * @param string $url
     * @param string $param
     * @return bool|mixed
     */
    function request_post($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }
        $postUrl = $url;
        $curlPost = $param;
        $ch = curl_init(); //初始化curl
        curl_setopt($ch, CURLOPT_URL, $postUrl); //抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0); //设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch); //运行curl
        curl_close($ch);
        return $data;
    }
    /**
     * 发送get请求
     * @param string $url
     * @return bool|mixed
     */
    function request_get($url = '')
    {
        if (empty($url)) {
            return false;
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }





}